package gemini.castor.ui.client.page.widget.identify;

import gemini.castor.ui.client.page.widget.NumberFieldStandard;
import gemini.castor.ui.client.page.widget.date.DateWidget;
import gemini.castor.ui.client.utils.UiConstants;

import java.util.Iterator;
import java.util.Set;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.validation.client.InvalidConstraint;
import com.google.gwt.validation.client.interfaces.IValidator;

public class IdentifyWidget extends Composite {

	@UiTemplate("IdentifyWidget.ui.xml")
	interface MyUiBinder extends UiBinder<Panel, IdentifyWidget> {
	}

	private static final MyUiBinder binder = GWT.create(MyUiBinder.class);

	private IValidator<IdentifyObject> validator;
	private IdentifyObject object;
	public void setIdentifyObject(IdentifyObject object) {
		this.object = object;
	}

	public IdentifyWidget() {
		initWidget(binder.createAndBindUi(this));
		validator = GWT.create(IdentifyObject.class);
		
		tbxNumber.setMaxLength(UiConstants.MAX_LEN_IDENTITY_NUMBER);
	}

	@UiField
	NumberFieldStandard tbxNumber;

	@UiField
	TextBox tbxPlace;

	@UiField
	DateWidget dwgDate;

	public boolean isValidate(){
		resetStyle();
		bind();
		boolean result = true;
		Set<InvalidConstraint<IdentifyObject>> invalidConstraints = validator.validate(object);
		Iterator<InvalidConstraint<IdentifyObject>> it = invalidConstraints
			.iterator();
		
		while (it.hasNext()) {
			if(result){
				result = false;
			}
			InvalidConstraint<IdentifyObject> ic = it.next();
			showError(ic.getItemName(), ic.getMessage());
		}
		
		return result;
	}
	
	private void showError(String widgetName, String errorString) {
		if (widgetName.equals("number")) {
			tbxNumber.addStyleDependentName("error");
		} else if (widgetName.equals("place")) {
			tbxPlace.addStyleDependentName("error");
		} 
	}
	
	public void bind(){
		object.setDate(dwgDate.getDateFromDateWidget());
		object.setNumber(tbxNumber.getValue());
		object.setPlace(tbxPlace.getValue());
	}
	
	public void reset(){
		resetValue();
		resetStyle();
	}
	
	private void resetValue() {
		tbxNumber.setValue("", true);
		tbxPlace.setValue("", true);
		dwgDate.reset();
	}
	
	private void resetStyle(){
		tbxNumber.removeStyleDependentName("error");
		tbxPlace.removeStyleDependentName("error");
	}
}
